package com.zp.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ArrayUtil;
import com.zp.common.core.constant.UserConstants;
import com.zp.common.core.controller.BaseController;
import com.zp.common.core.entity.R;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.log.annotation.Log;
import com.zp.common.log.enums.BusinessType;
import com.zp.system.api.entity.SysDept;
import com.zp.system.service.ISysDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 科室信息
 *
 * @author zhang peng
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/dept")
public class SysDeptController extends BaseController {

    private final ISysDeptService deptService;

    /**
     * 获取科室列表
     */
    @SaCheckPermission("system:dept:list")
    @GetMapping("/list")
    public R<List<SysDept>> list (SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return R.ok(depts);
    }


    /**
     * 查询科室列表（排除节点）
     *
     * @param deptId 科室ID
     */
    @SaCheckPermission("system:dept:list")
    @GetMapping("/list/exclude/{deptId}")
    public R<List<SysDept>> excludeChild (@PathVariable(value = "deptId", required = false) String deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> StringUtils.equals(d.getDeptId(), deptId) || ArrayUtil.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return R.ok(depts);
    }

    /**
     * 查询科室列表树
     *
     * @param sysDept deptId 科室ID
     */
    @SaCheckPermission("system:dept:list")
    @PostMapping("/list/deptTree")
    public R<Map<Object, Object>> getDeptTree (@RequestBody SysDept sysDept) {
        Map<Object, Object> map = new HashMap<>();
        List<SysDept> deptList = deptService.selectDeptList(sysDept);
        List<Tree<String>> list = deptService.selectDeptTreeList(sysDept);
        map.put("list", list);
        map.put("deptList", deptList.size());
        return R.ok(map);
    }

    /**
     * 根据科室编号获取详细信息
     *
     * @param deptId 科室ID
     */
    @SaCheckPermission("system:dept:query")
    @GetMapping(value = "/{deptId}")
    public R<SysDept> getInfo (@PathVariable String deptId) {
        deptService.checkDeptDataScope(deptId);
        return R.ok(deptService.selectDeptById(deptId));
    }

    /**
     * 新增科室
     */
    @SaCheckPermission("system:dept:add")
    @Log(title = "科室管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Void> add (@Validated @RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return R.fail("新增科室'" + dept.getDeptName() + "'失败，科室名称已存在");
        }
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptCodeUnique(dept))) {
            return R.fail("新增科室'" + dept.getDeptName() + "'失败，科室代码已存在");
        }
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改科室
     */
    @SaCheckPermission("system:dept:edit")
    @Log(title = "科室管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void> edit (@Validated @RequestBody SysDept dept) {
        String deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return R.fail("修改科室'" + dept.getDeptName() + "'失败，科室名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return R.fail("修改科室'" + dept.getDeptName() + "'失败，上级科室不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return R.fail("该科室包含未停用的子科室！");
        } else if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptCodeUnique(dept))) {
            return R.fail("修改科室'" + dept.getDeptName() + "'失败，科室代码已存在");
        }
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除科室
     */
    @SaCheckPermission("system:dept:remove")
    @Log(title = "科室管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public R<Void> remove (@PathVariable String deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return R.fail("存在下级科室,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return R.fail("科室存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }
}
